package grabbing.ticket.common.util.queue;

import grabbing.ticket.business.web.TicKetQuery;
import grabbing.ticket.common.util.redis.RedisTicketUtils;
import grabbing.ticket.common.util.thread.ThreadPoolManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * 抢票队列
 *
 * @author lcf
 */
@Component
public class TicketQueueUtils{
    /**
     * 请求队列
     */
    private static BlockingQueue<TicKetQuery> queue = new LinkedBlockingQueue<>(100);

    @Autowired
    private RedisTicketUtils ticketUtils;

    /**
     * 添加任务
     */
    public void addTask(long userId, int num) {
        boolean success = queue.offer(new TicKetQuery(userId, num));
        if (!success) {
            System.out.println("系统繁忙，请稍后重试");
        }
    }

    /**
     * 处理任务
     */
    public void dealTask() {
        ThreadPoolManager threadPoolHolder = ThreadPoolManager.newInstance();
        threadPoolHolder.addExecuteTask(() -> {
            try {
                while (true) {
                    TicKetQuery query = queue.take();
                    if (ticketUtils.get() <= 0) {
                        System.out.println("库存不足");
                    }else if (ticketUtils.decrement(query.getAmount())) {
                        System.out.println("抢票成功");
                    } else {
                        System.out.println("抢票失败");
                    }
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
    }
}
